package com.chenqi.tool.toast

import android.annotation.SuppressLint
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.Toast
import com.chenqi.tool.R

/**
 * 作者: CQ
 * 日期: 2021-07-06
 * 说明: 自定义toast居中显示
 */
class ToastUtils {

    companion object {
        @Volatile
        private var toastUtils: ToastUtils? = null

        fun getInstance(): ToastUtils {
            return toastUtils ?: synchronized(ToastUtils::class.java) {
                toastUtils ?: ToastUtils()
            }
        }
    }

    @SuppressLint("InflateParams")
    fun makeText(context: Context, content: String, duration: Int): Toast {
        val toast = Toast(context)
        val inflate = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val view = inflate.inflate(R.layout.toast_text, null)
        val text = view.findViewById<TextView>(R.id.text_show)
        text.text = content
        toast.duration = duration
        toast.setGravity(Gravity.CENTER, 0, 0)
        toast.view = view
        return toast
    }

    @SuppressLint("InflateParams")
    fun showText(context: Context, content: String) {
        val toast = Toast(context)
        val inflate = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val view = inflate.inflate(R.layout.toast_text, null)
        val text = view.findViewById<TextView>(R.id.text_show)
        text.text = content
        toast.duration = Toast.LENGTH_SHORT
        toast.setGravity(Gravity.CENTER, 0, 0)
        toast.view = view
        toast.show()
    }
}

fun Toast.showText(context: Context, content: String) {
    val inflate = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    val root = inflate.inflate(R.layout.toast_text, null)
    val text = root.findViewById<TextView>(R.id.text_show)
    text.text = content
    duration = Toast.LENGTH_SHORT
    setGravity(Gravity.CENTER, 0, 0)
    view = root
    show()
}